import { useEffect } from "react";
import { Table, Modal, message, Row, Col, Space, Popconfirm, Badge, Tooltip } from "antd";
import { Card as SemiCard, List, ButtonGroup, Button } from "@douyinfe/semi-ui";
import { IconRefresh, IconEyeOpened, IconPlus, IconEdit, IconGlobeStroke } from "@douyinfe/semi-icons";
import { useModel } from "umi";
import { useReactive } from "ahooks";

import AddOrganizationReferenceDatabaseModal from "../../components/resources/organizationReferenceDatabase.add";
import EditOrganizationReferenceDatabaseModal from "../../components/resources/organizationReferenceDatabase.edit";

const { Column } = Table;

const OrganizationReferenceDatabase = () => {
    const { windowInnerHeight, graphqlFetchPlatform, remoteData, BNTApplicationResourceCenterServiceURL, BNTApplicationOperationCenterUrls, runEnv } = useModel("global");
    const { setModalVisible, setModalTitle, setModalWidth, setModalComponent } = useModel("global.modal");
    const { baseInfo } = useModel("person.info");

    const state = useReactive({
        loading: false,
        databases: [],
        selectedDatabase: {},
        versions: [],
        versionloading: false,
        submitLoading: false,
    });

    const loadData = async () => {
        state.loading = true;
        let query = `query { a:allOrganizationReferenceDatabases { totalCount nodes { databaseName graphqlServiceName heartBeatParams title uuid } } }`;
        let res = await graphqlFetchPlatform({ query, variables: {} });
        if (res?.a?.totalCount > 0) {
            state.databases = res.a.nodes;
            state.selectedDatabase = state.selectedDatabase.uuid ? state.databases.find((item) => item.uuid === state.selectedDatabase.uuid) : res.a.nodes[0];
        }
        state.loading = false;
    };

    useEffect(() => {
        loadData();
    }, []);

    const loadVersions = async () => {
        state.versionloading = true;
        let query = `query MyQuery($databaseName: String!) { a: allOrganizationReferenceDatabaseVersions( condition: {databaseName: $databaseName} orderBy: CREATE_TIME_DESC ) {
            totalCount nodes { compareVersion databaseName structureObjects patchData versionNo uuid createTime creater publishRecord } }
        }`;
        let res = await graphqlFetchPlatform({ query, variables: { databaseName: state.selectedDatabase.databaseName } });
        state.versions = res?.a?.nodes || [];
        state.versionloading = false;
    };

    useEffect(() => {
        state.selectedDatabase?.uuid && loadVersions();
    }, [state.selectedDatabase]);

    const openAddOrganizationReferenceDatabaseModal = () => {
        setModalTitle("添加组织参考数据库信息");
        setModalWidth(650);
        setModalComponent(<AddOrganizationReferenceDatabaseModal reloadData={loadData} />);
        setModalVisible(true);
    };

    const openEditOrganizationReferenceDatabaseModal = () => {
        setModalTitle("编辑组织参考数据库信息");
        setModalWidth(650);
        setModalComponent(<EditOrganizationReferenceDatabaseModal record={state.selectedDatabase} reloadData={loadData} />);
        setModalVisible(true);
    };

    const openDataDetail = (record) => {
        setModalTitle("查看补丁数据");
        setModalWidth(650);
        setModalComponent(<DataDetailModal record={record} />);
        setModalVisible(true);
    };

    const addVersion = async () => {
        Modal.confirm({
            content: `确认要添加新版本信息吗?`,
            okButtonProps: { loading: state.submitLoading },
            onOk: async () => {
                state.submitLoading = true;
                let res = await remoteData({
                    object: "bnt-application-resource-center-service",
                    serviceUrl: BNTApplicationResourceCenterServiceURL,
                    serviceName: "/resource/referenceDatabase/organization/addVersion",
                    params: {
                        databaseName: state.selectedDatabase.databaseName,
                        creater: { uuid: baseInfo.uuid, name: baseInfo.realName },
                    },
                });
                if (res) {
                    message.success("成功创建新的组织数据库结构版本信息");
                    loadVersions();
                }
                state.submitLoading = false;
            },
        });
    };

    const onlineRunEnv = {
        development: [
            { title: "开发环境", runEnv: "dev", url: BNTApplicationOperationCenterUrls.dev },
            { title: "测试环境", runEnv: "testing", url: BNTApplicationOperationCenterUrls.testing },
        ],
        dev: [
            { title: "开发环境", runEnv: "dev", url: BNTApplicationOperationCenterUrls.dev },
            { title: "测试环境", runEnv: "testing", url: BNTApplicationOperationCenterUrls.testing },
        ],
        testing: [
            { title: "测试环境", runEnv: "testing", url: BNTApplicationOperationCenterUrls.testing },
            { title: "生产环境", runEnv: "production", url: BNTApplicationOperationCenterUrls.production },
        ],
        production: [],
    };

    const submitVersionPublish = async (operatorCenter, version) => {
        state.submitLoading = true;
        let res = await remoteData({
            object: "bnt-application-operation-center-service",
            serviceUrl: operatorCenter.url,
            serviceName: "/resource/referenceDatabase/organization/saveVersion",
            params: { database: state.selectedDatabase, version },
        });
        if (res) {
            let query = `mutation MyMutation($uuid: UUID!, $publishRecord: JSON!) {
                updateOrganizationReferenceDatabaseVersionByUuid(
                  input: { uuid: $uuid organizationReferenceDatabaseVersionPatch: { publishRecord: $publishRecord }
                } ) { clientMutationId }
            }`;
            let res = await graphqlFetchPlatform({
                query,
                variables: {
                    uuid: version.uuid,
                    publishRecord: {
                        ...version.publishRecord,
                        [operatorCenter.runEnv]: {
                            time: new Date().getUTCTime(),
                            uuid: baseInfo.uuid,
                            name: baseInfo.realName,
                        },
                    },
                },
            });
            if (res) {
                message.success("数据库版本发布成功");
                loadVersions();
            }
        }
        state.submitLoading = false;
    };

    const cardBodyHeight = windowInnerHeight - 90 - 20 - 54;

    return (
        <Row gutter={10} style={{ padding: 10, display: "flex" }}>
            <Col span={8}>
                <SemiCard
                    title={<span style={{ lineHeight: "32px", fontSize: 16, fontWeight: 600 }}>组织参考数据库列表</span>}
                    headerExtraContent={
                        <ButtonGroup>
                            <Button icon={<IconPlus />} onClick={openAddOrganizationReferenceDatabaseModal}></Button>
                            <Button icon={<IconRefresh />} onClick={loadData}></Button>
                        </ButtonGroup>
                    }
                    headerStyle={{ padding: "10px 14px" }}
                    shadows="always"
                    bordered={false}
                    bodyStyle={{ padding: 1, height: cardBodyHeight, overflow: "auto" }}
                >
                    <List
                        loading={state.loading}
                        dataSource={state.databases}
                        renderItem={(item, index) => {
                            return (
                                <List.Item
                                    key={index}
                                    className={`list-item ${state.selectedDatabase?.uuid === item?.uuid ? "list-selected-item" : ""}`}
                                    main={
                                        <div>
                                            <div>
                                                {item.title} - {item.graphqlServiceName}
                                            </div>
                                            <div>{item.databaseName}</div>
                                        </div>
                                    }
                                    onClick={() => (state.selectedDatabase = item)}
                                ></List.Item>
                            );
                        }}
                    />
                </SemiCard>
            </Col>
            <Col span={16}>
                <SemiCard
                    title={<span style={{ lineHeight: "32px", fontSize: 16, fontWeight: 600 }}>组织参考数据库结构版本列表</span>}
                    headerExtraContent={
                        <ButtonGroup>
                            {state.selectedDatabase?.uuid && <Button icon={<IconEdit />} onClick={openEditOrganizationReferenceDatabaseModal}></Button>}
                            {state.selectedDatabase?.uuid && <Button icon={<IconPlus />} onClick={addVersion}></Button>}
                            <Button icon={<IconRefresh />} onClick={loadVersions}></Button>
                        </ButtonGroup>
                    }
                    headerStyle={{ padding: "10px 14px" }}
                    shadows="always"
                    bordered={false}
                    bodyStyle={{ padding: 0, height: cardBodyHeight, overflow: "auto" }}
                >
                    <Table loading={state.versionloading} dataSource={state.versions} rowKey="uuid" bordered size="small" pagination={false} scroll={{ y: cardBodyHeight - 40 }}>
                        <Column title="序号" align="center" width={60} render={(_, r, i) => i + 1} />
                        <Column title="版本号" dataIndex="versionNo" align="center" />
                        <Column title="创建人" dataIndex="creater" align="center" render={(_, r, i) => _.name} />
                        <Column title="创建时间" dataIndex="createTime" align="center" width={160} render={(_, r, i) => formatUTCTime(_)} />
                        <Column
                            title="补丁数据"
                            dataIndex="patchData"
                            align="center"
                            width={100}
                            render={(_, r, i) => _ && _.length > 0 && <Button theme="borderless" icon={<IconEyeOpened />} onClick={() => openDataDetail(_)}></Button>}
                        />
                        <Column title="比较的版本号" dataIndex="compareVersion" align="center" width={120} />
                        <Column
                            title="发布状态"
                            dataIndex="publishRecord"
                            align="center"
                            width={100}
                            render={(_, r, i) => (
                                <Space>
                                    <Tooltip title={_["dev"]?.uuid ? `${_["dev"]?.name} ${formatUTCTime(_["dev"]?.time)}` : ""}>
                                        <Badge color={_["dev"]?.uuid ? "green" : "red"} />
                                    </Tooltip>
                                    <Tooltip title={_["testing"]?.uuid ? `${_["testing"]?.name} ${formatUTCTime(_["testing"]?.time)}` : ""}>
                                        <Badge color={_["testing"]?.uuid ? "green" : "red"} />
                                    </Tooltip>
                                    <Tooltip title={_["production"]?.uuid ? `${_["production"]?.name} ${formatUTCTime(_["production"]?.time)}` : ""}>
                                        <Badge color={_["production"]?.uuid ? "green" : "red"} />
                                    </Tooltip>
                                </Space>
                            )}
                        />
                        <Column
                            title="操作"
                            align="center"
                            width={120}
                            render={(_, r) => (
                                <Space size={0}>
                                    {onlineRunEnv[runEnv].map((item, index) => (
                                        <Popconfirm
                                            key={index}
                                            placement="topRight"
                                            title={`确认要发布数据库版本到应用运营中心吗?`}
                                            okButtonProps={{ loading: state.submitLoading }}
                                            onConfirm={() => submitVersionPublish(item, r)}
                                        >
                                            <Button key={index} theme="borderless" icon={<IconGlobeStroke />} title={`发布到${item.title}`}></Button>
                                        </Popconfirm>
                                    ))}
                                </Space>
                            )}
                        />
                    </Table>
                </SemiCard>
            </Col>
        </Row>
    );
};

const DataDetailModal = ({ record }) => {
    return (
        <div>
            <List
                bordered
                dataSource={record}
                renderItem={(item) => (
                    <List.Item>
                        <div>{item}</div>
                    </List.Item>
                )}
            />
        </div>
    );
};

export default OrganizationReferenceDatabase;
